#include "ses_led.h"
#include "ses_lcd.h"
#include "ses_button.h"
#include "ses_timer.h"
#include "ses_scheduler.h"



/*
 * Main class for running tasks on scheduler.
 *
 * Provides functions that are to be executed via the scheduler.
 */



volatile static bool clock_stopped 	= false; // control stopping of stop clock
volatile static uint8_t sec 		= 0;	 // seconds for stop clock
volatile static uint8_t dec 		= 0;	 // first decimal for stop clock



/*
 * Toogle green LED and add self to scheduler to be executed again.
 */
void green_toggle() {
	led_greenToggle();
	scheduler_add(green_toggle, 500);
}

/*
 * Toggle yellow LED if joystick was pressed.
 *
 * joystick_pressed() is important for debouncing.
 */
void yellow_toggle() {
	if (joystick_pressed()) {
		led_yellowToggle();
	}
}

/*
 * Add yellow_toggle to scheduler with a debouncing delay of 20 ms.
 */
void yellow_toggle_with_debounce() {
	scheduler_add(yellow_toggle, 20);
}

/*
 * Increments displayed clock every 100 ms.
 *
 * Global variable clock_stopped will stop the clock from incrementing.
 */
void increment_stop_clock() {
	scheduler_add(increment_stop_clock, 100);
	if (!clock_stopped) {
		++dec;
		if (dec == 10) {
			++sec;
			dec = 0;
		}
		lcd_setCursor(7, 2);
		fprintf(lcdout, "%d.%d\n", sec, dec);
	}
}

/*
 * Toggles boolean variable clock_stopped.
 *
 * rotary_pressed() is important for debouncing.
 */
void stop_clock() {
	if (rotary_pressed()) {
		clock_stopped = !clock_stopped;
	}
}

/*
 * Calls stop_clock() after a debouncing period of 20 ms.
 */
void stop_clock_with_debounce() {
	scheduler_add(stop_clock, 50);
}

int main() {

	// init LEDs
	led_allInit();

	// init buttons
	button_init();
	button_setJoystickButtonCallback(yellow_toggle_with_debounce);
	button_setRotaryButtonCallback(stop_clock);

	// init LCD
	lcd_init();

	// init scheduler
	scheduler_init();
	scheduler_add(green_toggle, 500);
	scheduler_add(increment_stop_clock, 0);

	// run
	scheduler_run();

}
